<template>
    <div @dblclick="editMode = true" class="cust-text-node" ref="inputRef">
        <span class="cust-text" :class="{ 'isHidden': editMode }" ref="textSpan">{{ text }}</span>
        <el-input :class="{ 'isHidden': !editMode }" size="small" v-model="text" @blur="saveText"
            @keydown.enter="outFucos" @mousemove.stop style="min-width: 100px;" />
    </div>
</template>

<script setup lang="ts">
import { EventType } from '@logicflow/core'
import { vueNodesMap } from '@logicflow/vue-node-registry'
const inputRef = ref<HTMLDivElement | null>(null)
let inputPanel: any;
const editMode = ref(false);
const text = ref('');
const getGraph = inject<() => any>('getGraph');
const getNode = inject<() => any>('getNode');
let node: any;
let eventCenter: any;

const textSpan = ref<HTMLDivElement | null>(null);
function saveText() {
    // 关闭编辑模式    
    // eventCenter.emit('custNode:dragstart-on');
    editMode.value = false;       
    eventCenter.emit('custNode:change', {
        id: node.id,
        customNodeName: text.value,
    });
}
function outFucos() {
    if (inputPanel) {
        inputPanel.blur();
    }
}
onMounted(() => {
    // 在组件打开时设置焦点,获取焦点
    inputPanel = inputRef.value?.querySelector('input');    
    if (inputPanel) {
        const inputFucos = () => {
            nextTick(() => {
                inputPanel.focus();
                eventCenter.emit('custNode:onchanging', {
                    id: node.id,
                    customNodeName: text.value,
                });
            });
        };
        // inputFucos();
        watch(editMode, (newValue) => {
            if (newValue) {
                inputFucos();
            }
        })
    }
    if (getGraph && getNode) {
        eventCenter = getGraph().eventCenter
        node = getNode()
        text.value = node.properties.customNodeName
        eventCenter.on(EventType.NODE_PROPERTIES_CHANGE, (eventData: any) => {            
            const keys = eventData.keys as string[]
            const content = vueNodesMap[node.type]            
            if (content && eventData.id === node.id) {                
                const { effect } = content                
                if (!effect || keys.some((key) => effect.includes(key))) {                    
                    text.value = eventData.properties?.customNodeName || ''
                }
            }
        })
    }
    const lfNodeContentRef = inputRef.value?.closest('.lf-node-content')
    if(lfNodeContentRef){
        lfNodeContentRef.classList.add('cust-text-node-content');
    }    
});
</script>
<style scoped lang="scss">
.cust-text-node {
    display: flex;
    height: 28px;
    line-height: 28px;
    align-items: center;

    .cust-text {
        font-size: 12px;
        color: var(--el-text-color-primary);
        padding: 1px 7px;
        white-space: nowrap;
    }
}
.isHidden {
    display: none;
}
</style>